package com.hoshiicloud.goods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentParam;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.goods.entity.sku.ExtSku;
import com.hoshiicloud.goods.param.ListSkuSpuParam;
import com.hoshiicloud.goods.param.sku.ExtSkuAddParam;
import com.hoshiicloud.goods.param.sku.ExtSkuQueryParam;
import com.hoshiicloud.goods.param.sku.ExtSkuUpdateParam;
import com.hoshiicloud.goods.service.ExtSkuService;
import com.hoshiicloud.goods.vo.ListSpuSkuVo;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 扩展商品SKU 控制器
 * </p>
 * 2019-06-04 zhangshuhu
 */
@Slf4j
@RestController
@RequestMapping("/goods/ext-sku")
@Api(value = "扩展商品SKU", tags = {"扩展商品SKU"})
public class ExtSkuController {
    private final ExtSkuService extSkuService;
    public ExtSkuController(ExtSkuService extSkuService) {
        this.extSkuService = extSkuService;
    }

    @ApiOperation(value = "分页查询扩展商品SKU")
    @PostMapping("/query/page")
    public Response<Page<ExtSku>> page(@RequestBody ExtSkuQueryParam param) {
        try {
            log.info("分页查询扩展商品SKU");
            QueryWrapper<ExtSku> queryWrapper = getExtSkuQueryWrapper(param);
            Page<ExtSku> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = "ExtSkuQueryParam{"+param.toString() + "},Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            return Response.data(extSkuService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询扩展商品SKU异常", e);
            return Response.failed("分页查询扩展商品SKU异常");
        }
    }

    @ApiOperation(value = "分页查询扩展商品SKU")
    @PostMapping("/listByParam")
    public Response<List<ExtSku>> listByParam(@RequestBody ExtSkuQueryParam param) {
        try {
            log.info("查询扩展SKU列表");
            QueryWrapper<ExtSku> queryWrapper = getExtSkuQueryWrapper(param);
            String key = param.toString();
            return Response.data(extSkuService.listByParam(queryWrapper, key));
        } catch (Exception e) {
            log.error("查询扩展SKU列表异常", e);
            return Response.failed("查询扩展SKU列表");
        }
    }


    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询扩展商品SKU")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response<ExtSku> queryById(@PathVariable("id") Long id) {
        return Response.data(extSkuService.getById(id));
    }

    /**
     * @param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 根据店铺ID和spuId查询扩展SPU
     */
    @GetMapping("/getOneByStoreIdAndSkuId")
    @ApiOperation(value = "根据店铺ID和skuId查询扩展SPU")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuId", value = "skuId"),
            @ApiImplicitParam(name = "storeId", value = "店铺Id"),
    })
    public Response<ExtSku> getOneByStoreIdAndSkuId(@RequestParam Map<String,Object> map) {
        QueryWrapper<ExtSku> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq( ExtSku::getStoreId ,Long.valueOf(map.get("storeId").toString()))
                .eq(ExtSku::getDeleted,0)
                .eq( ExtSku::getSkuId ,Long.valueOf(map.get("skuId").toString()));
        return Response.data(extSkuService.getOne(queryWrapper)
        );
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 新增
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增扩展商品SKU")
    public Response save(@RequestBody  ExtSkuAddParam param) {

        // Bean数据转换
        ExtSku entity;
        try {
            entity = BeanUtils.covertType(param, ExtSku.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(extSkuService.save(entity));
    }

    @PostMapping("/saveExtSku")
    @ApiOperation(value = "新增分店扩展商品SKU")
    public Response<ExtSku> saveExtSku(@RequestBody @Valid ExtSkuAddParam param) {
        // Bean数据转换
        ExtSku entity;
        try {
            entity = BeanUtils.covertType(param, ExtSku.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(extSkuService.saveExtSku(entity));
    }

    /**
     * @param param
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 修改扩展商品SKU
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改扩展商品SKU")
    public Response update(@RequestBody @Valid ExtSkuUpdateParam param) {
        // Bean数据转换
        ExtSku entity;
        try {
            entity = BeanUtils.covertType(param, ExtSku.class);
        } catch (Exception e) {
            log.error("Bean转换异常", e);
            return Response.failed("Bean转换异常");
        }
        return Response.data(extSkuService.updateById(entity));
    }

    /**
     * @param id
     * @return com.hoshiicloud.common.rpc.Response
     * @description: 删除扩展商品SKU
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除扩展商品SKU")
    @ApiParam(name = "id", value = "主键ID", required = true)
    public Response delete(@PathVariable("id") Long id) {
        return Response.data(extSkuService.deleteById(id));
    }

    /**
     * @Author:campchen
     * @Description: StringUtils.join(ids, " ") 为缓存中添加唯一KEY  如不合适可选择更好方法
     * @Date:上午 10:18 2019/5/11
     * @Param: ids
     * @return: com.hoshiicloud.common.rpc.Response
     */
    @ApiOperation(value = "根据id集合查询扩展商品SKU")
    @GetMapping("/getByIds")
    public Response getByIds(@RequestParam List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Response.failed("id不能为空");
        }
        ids.sort(null);
        return Response.data(extSkuService.getByIds(ids, StringUtils.join(ids, "")));
    }

    /**
     * 根据spuid获取sku最低价
     *
     * @param param 查询参数
     * @return Response<Map < String, Object>>
     */
    @ApiOperation(value = "根据spuid获取sku最低价")
    @PostMapping("/listSkuMiniPrice")
    public Response<Map<String, Object>> listSkuMiniPrice(@RequestBody ExtSkuQueryParam param) {
        try {
            // TODO 修改了代码在queryWrapper中添加一个 new ExtSku
            ExtSku data = BeanUtils.covertType(param, ExtSku.class);
            log.info("根据spuid获取sku最低价");
            QueryWrapper<ExtSku> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(null != param.getSpuId(), "spu_id", param.getSpuId());
            queryWrapper.select(BeanUtils.getSqlSelect(ExtSku.class));
            queryWrapper.setEntity(data);
            return Response.data(extSkuService.listSkuMiniPrice(queryWrapper));
        } catch (ServiceException e) {
            return Response.failed(e.getError().getMsg());
        } catch (Exception e) {
            log.error("根据spuid获取sku最低价异常", e);
            return Response.failed("根据spuid获取sku最低价异常");
        }
    }

    @ApiOperation(value = "获取各店铺分配的sku数量")
    @GetMapping("/getStoreSkuNum")
    public Response<Map<String,String>> getStoreSkuNum(@RequestParam List<Long> storeIds) {
        if (CollectionUtils.isEmpty(storeIds)) {
            return Response.failed("店铺id不能为空");
        }
        storeIds.sort(null);
        return Response.data(extSkuService.getStoreSkuNum(storeIds,StringUtils.join(storeIds, "")));
    }

    @ApiOperation(value = "根据店铺id查询 各店铺的skuId")
    @GetMapping("/queryStoresAndBaseSkuIds")
    public Response<Map<String, List<String>>> queryStoresAndBaseSpuIds(@RequestParam("storeIds") List<Long> storeIds){
        if(CollectionUtils.isEmpty(storeIds)){
            return Response.failed("店铺ID集合不能为空");
        }
        storeIds.sort(null);
        return Response.data(extSkuService.queryStoresAndBaseSkuIds(storeIds, StringUtils.join(storeIds, "")));
    }

    @ApiOperation(value = "批量保存")
    @PostMapping("/saveBatch")
    public Response<Boolean>  saveBatch(@RequestBody List<ExtSku> list){
        if(CollectionUtils.isEmpty(list)){
            return Response.data(true);
        }
        return Response.data(extSkuService.saveBatch1(list));
    }

    @ApiOperation(value = "批量更新")
    @PostMapping("/updateBatch")
    public Response updateBatch(@RequestBody OmnipotentParam<ExtSku> param) {
        return Response.data(extSkuService.omniExtSkuUpdate(param));
    }

    @ApiOperation(value = "批量查询")
    @PostMapping("/queryBatch")
    public Response queryBatch(@RequestBody List<OmnipotentWrapper> params) {
        return Response.data(extSkuService.queryBatch(params));
    }


    @ApiOperation(value = "获取分店可添加的sku分页列表")
    @PostMapping("/getBranchStoreCanAddSkuPage")
    public Response<Page<ListSpuSkuVo>> getBranchStoreCanAddSkuPage(@RequestBody ListSkuSpuParam param){
        return Response.data(extSkuService.getBranchStoreCanAddSkuPage(param));
    }



    private QueryWrapper<ExtSku> getExtSkuQueryWrapper(ExtSkuQueryParam param) {
        QueryWrapper<ExtSku> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq((param.getCompanyId() != null), ExtSku::getCompanyId, param.getCompanyId())
                .eq((param.getPlatformId() != null ), ExtSku::getPlatformId, param.getPlatformId())
                .eq((param.getStoreId() != null ), ExtSku::getStoreId, param.getStoreId())
                .eq((param.getSpuId() != null ), ExtSku::getSpuId, param.getSpuId())
                .eq((param.getSkuId() != null), ExtSku::getSkuId, param.getSkuId())
                .eq(StringUtils.isNotBlank(param.getSkuTitle()), ExtSku::getSkuTitle, param.getSkuTitle())
                .eq((param.getSalePrice() != null), ExtSku::getSalePrice, param.getSalePrice())
                .eq((param.getMarketPrice() != null), ExtSku::getMarketPrice, param.getMarketPrice())
                .eq((param.getCostPrice() != null), ExtSku::getCostPrice, param.getCostPrice())
                .eq((param.getVendorId() != null), ExtSku::getVendorId, param.getVendorId())
                .eq(StringUtils.isNotBlank(param.getSkuImage()), ExtSku::getSkuImage, param.getSkuImage())
                .eq(StringUtils.isNotBlank(param.getExtendProperty()), ExtSku::getExtendProperty, param.getExtendProperty())
                .eq(StringUtils.isNotBlank(param.getExtendSpec()), ExtSku::getExtendSpec, param.getExtendSpec())
                .eq((param.getDispatchPolicy() != null), ExtSku::getDispatchPolicy, param.getDispatchPolicy())
                .eq((param.getDispatchWhid() != null), ExtSku::getDispatchWhid, param.getDispatchWhid())
                .eq(StringUtils.isNotBlank(param.getDispatchWhids()), ExtSku::getDispatchWhids, param.getDispatchWhids())
                .eq((param.getStoreEnough() != null), ExtSku::getStoreEnough, param.getStoreEnough())
                .eq((param.getStatus() != null), ExtSku::getStatus, param.getStatus())
                .eq((param.getDeleted() != null), ExtSku::getDeleted, param.getDeleted());
        return queryWrapper;
    }


}
